import json
import logging.handlers
import os

import pymysql
from bs4 import BeautifulSoup

from config import DIR_PATH


def common_assert(response, status_code=None, expect_json=None, expect_text=None):
    if status_code:
        assert response.status_code == status_code, "预期状态码：{} != 实际状态码：{}".format(status_code,
                                                                                            response.status_code)
    if expect_json:
        assert expect_json in response.json().get("description"), "实际结果：{} 不包含 预期结果：{}".format(
            response.json().get("description"), expect_json)
    if expect_text:
        assert expect_text in response.text, "实际结果：{} 不包含 预期结果：{}".format(
            response.text, expect_text)


def read_json(filename, key):
    filepath = DIR_PATH + os.sep + "data" + os.sep + filename
    arrs = []
    with open(filepath, encoding="utf-8") as f:
        result = json.load(f)
        for data in result.get(key):
            arrs.append(tuple(data.values())[1:])
        return arrs


def html_parser(result):
    html = result.json().get("description").get("form")
    bs = BeautifulSoup(html, "html.parser")
    url = bs.form.get("action")
    print("提取的url：" + url)
    data = {}
    for input in bs.find_all("input"):
        data[input.get("name")] = input.get("value")
    return url, data


def connect_mysql(sql):
    conn = None
    cursor = None
    try:
        conn = pymysql.connect(host="121.43.169.97", user="student", password="P2P_student_2023",
                               database="czbk_member", port=3306, charset="utf8", autocommit=True)
        cursor = conn.cursor()
        cursor.execute(sql)
        if sql.lower().split()[0] == "select":
            return cursor.fetchall()
    except Exception as e:
        print("出错了：", e)
        conn.rollback()
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()
# 清楚数据
def clear_data():
    sql_1 = """
        delete info.* from mb_member as mb inner join mb_member_info  as info on info.member_id = mb.id where mb.phone in ("15937079911","15937079912","15937079913","15937079914");
    """
    connect_mysql(sql_1)
    sql_2 = """
        delete login.* from mb_member as mb inner join mb_member_login_log  as login on login.member_id = mb.id where mb.phone in ("15937079911","15937079912","15937079913","15937079914");
        """
    connect_mysql(sql_2)
    sql_3 = """
        delete from mb_member where phone in ("15937079911","15937079912","15937079913","15937079914");
        """
    connect_mysql(sql_3)
    sql_4 = """
        delete from mb_member_register_log where phone in ("15937079911","15937079912","15937079913","15937079914");
        """
    connect_mysql(sql_4)

class GetLog:
    log = None

    @classmethod
    def get_log(cls):
        if cls.log is None:
            # 获取日志器
            cls.log = logging.getLogger()
            # 设置入口级别
            cls.log.setLevel(logging.INFO)
            # 设置文件
            filepath = DIR_PATH + os.sep + "log" + os.sep + "p2p.log"
            tf = logging.handlers.TimedRotatingFileHandler(filename=filepath, when="midnight", interval=1,
                                                           backupCount=3, encoding="utf-8")
            # 设置格式
            fm = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fmt = logging.Formatter(fm)
            # 将格式器添加到文件中
            tf.setFormatter(fmt)
            # 将文件添加到日志器中
            cls.log.addHandler(tf)
        return cls.log


log = GetLog.get_log()

if __name__ == '__main__':
    # print(read_json("register_login.json", "login_status"))
    # GetLog.get_log().info("信息级别测试")
    # GetLog.get_log().error("error级别测试")
    # sql_1 = "select * from mb_member as mb inner join mb_member_info  as info on info.member_id = mb.id where mb.phone in ('15937079911')"
    # print(connect_mysql(sql_1))
    # os.system('allure generate ./report -o ./reports --clean')
    os.system("allure open ./report")